package example

import (
	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/widget"
	"github.com/davyxu/ulexer"
)

func Ulexer(a fyne.App) {
	w := a.NewWindow("Ulexer https://hub.fastgit.org/davyxu/ulexer")
	w.Resize(fyne.NewSize(900, 600))
	msg := widget.NewLabel("")
	input := widget.NewMultiLineEntry()
	input1 := widget.NewMultiLineEntry()
	result := widget.NewMultiLineEntry()
	var containStr string
	input.SetText("game#1@dev")
	mapp := map[string]ulexer.Matcher{
		"匹配标识符":         ulexer.Identifier(),
		"匹配正数, 负数, 浮点数": ulexer.Numeral(),
		"匹配true/false":  ulexer.Bool(),
		"匹配C块注释":        ulexer.CBlockComment(),
		"匹配C的行注释":       ulexer.CLineComment(),
		"匹配流结束":         ulexer.FileEnd(),
		"匹配十六进制":        ulexer.Hex(),
		"匹配有符号整数":       ulexer.Integer(),
		"匹配行结尾":         ulexer.LineEnd(),
		"匹配字符串":         ulexer.String(),
		"匹配数字, 无符号整形":   ulexer.UInteger(),
		"匹配Unix的行注释":    ulexer.UnixLineComment(),
		"匹配空白符":         ulexer.WhiteSpace(),
		"包含字面量":         ulexer.Contain(containStr),
	}
	options:=widget.NewSelect(getKeys(mapp),func(s string) {})
	btn := widget.NewButton("do", func() {
		if input.Text != "" {
			containStr = input1.Text
		}
		if options.Selected==""{
				msg.SetText("please input what u want")
			return
		}
		lex := ulexer.NewLexer(input.Text)
		ulexer.Try(lex, func(lex *ulexer.Lexer) {
			tokn := ulexer.Expect(lex, mapp[options.Selected])
			if tokn != nil {
				result.SetText(tokn.String())
				msg.SetText("success")
			} else {
				result.SetText("")
				msg.SetText("find nothing")
			}
		})

		/* ulexer.Try(lex,func(lex *ulexer.Lexer) {

		   }) */
	})
	top := container.NewVBox(input1, options, btn)
	c := container.NewBorder(top, msg, nil, nil,
		container.NewHSplit(input, result))
	w.SetContent(c)
	w.CenterOnScreen()
	w.Show()
}
func getKeys(m map[string]ulexer.Matcher) []string {
	// 数组默认长度为map长度,后面append时,不需要重新申请内存和拷贝,效率很高
	j := 0
	keys := make([]string, len(m))
	for k := range m {
		keys[j] = k
		j++
	}
	return keys
}
